package com.cesce.batch.cobros.items.listeners;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.annotation.AfterWrite;
import org.springframework.batch.core.annotation.BeforeProcess;
import org.springframework.batch.core.annotation.OnProcessError;
import org.springframework.batch.core.annotation.OnReadError;
import org.springframework.batch.core.annotation.OnWriteError;

import com.cesce.batch.cobros.reverse.Cobcomunicados;
import com.cesce.batch.cobros.reverse.Cobregistro;

public class CobrosListener {

	protected final Log logger = LogFactory.getLog(getClass());
   
	protected StringWriter sw = new StringWriter();
	protected PrintWriter pw = new PrintWriter(sw);
	
	protected Map<BigDecimal,Integer> count=new HashMap<BigDecimal,Integer>();
	
    
	@OnProcessError
	public void onProcessError(Object item, Exception e) {
	    e.printStackTrace(pw);
    	logger.error("PROCESS ERROR: " +  e.getClass() + ": "  + e.getMessage() + ":" + item + ": " + sw); 
    }
	
	@OnReadError
	public void onReadError(Exception e) {
	    e.printStackTrace(pw);
    	logger.error("READ ERROR: " +  e.getClass() + ": "  + e.getMessage() + ": " + sw); 
    }	

	@OnWriteError
	public void onWriteError(Exception e, List<Object> items) {
	    e.printStackTrace(pw);
    	logger.error("WRITE ERROR: " +  e.getClass() + ": "  + e.getMessage() + ":" + items + ": " + sw); 
    }		
	
	
	@BeforeProcess
	public void beforeProcess(Object item) {
		logger.info("Processing items: " + addCount(item) + ": " + item);   	
    }

	@AfterWrite
	public void afterWrite(List<Object> items) {
		
		if(items.size()>0)	logger.info("Written items from: " + getCount(items.get(0)) + " to " + getCount(items.get(items.size()-1)) + ": " + items);
		else logger.info("Nothing to write");
    }
	

	private Integer addCount(Object item) {
		
		BigDecimal id = new BigDecimal(-1);
		
		if(item instanceof Cobcomunicados) {
			Cobcomunicados com = (Cobcomunicados)item;
			id=com.getIdregistro().getIdregistro();
		} 
		
		if(count.get(id)==null) count.put(id, 0);
		else count.put(id,count.get(id) + 1);
		return count.get(id);
	}


	private Integer getCount(Object item) {
		BigDecimal id = new BigDecimal(-1);
		
		if(item instanceof Cobcomunicados) {
			Cobcomunicados com = (Cobcomunicados)item;
			id=com.getIdregistro().getIdregistro();
		} 
		
		return (count.get(id)==null?0:count.get(id));
	}

	
}
